package com.dpwgc.easywebpay.module.alipay.service;

import com.alipay.api.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dpwgc.easywebpay.base.dao.Order;
import com.dpwgc.easywebpay.base.mapper.OrderMapper;
import com.dpwgc.easywebpay.module.alipay.util.PayUtil;
import com.dpwgc.easywebpay.base.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Collections;
import java.util.List;

/**
 * 支付宝pc网页支付
 */
@Service
public class OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    PayUtil payUtil;

    /**
     * 用户下单
     * @param order 订单信息
     * @return ResultUtil<Order>
     * @throws AlipayApiException
     */
    public ResultUtil<Order> buy(Order order) throws AlipayApiException {

        ResultUtil<Order> resultUtil = new ResultUtil<>();

        //调用支付宝网页支付接口，创建订单，获取支付页面的html字符串
        String payPage = payUtil.webPay(order.getOrderNo(),order.getPrice(),order.getSubject());

        order.setPage(payPage); //将web支付页面存入数据库

        try {
            //将订单插入数据库
            int i = orderMapper.insert(order);

            if(i>0){
                resultUtil.setCode(200);
                resultUtil.setMsg("下单成功");
                resultUtil.setData(order);//返回订单信息
                return resultUtil;
            }

            //设置手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            resultUtil.setCode(100);
            resultUtil.setMsg("下单失败");
            return resultUtil;

        } catch (Exception e){

            //设置手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            resultUtil.setCode(100);
            resultUtil.setMsg("下单失败");
            return resultUtil;
        }
    }

    /**
     * 获取订单支付页面
     * @param orderId 订单id
     * @return String
     */
    public String getPayPage(Long orderId) {
        QueryWrapper<Order> queryOrder = new QueryWrapper<>();
        queryOrder.eq("id",orderId);
        Order order = orderMapper.selectOne(queryOrder);

        return order.getPage();
    }

    /**
     * 根据用户id获取用户订单列表（同时检查订单状态）
     * @param userId 用户id
     * @return ResultUtil<Object>
     */
    public ResultUtil<Object> list(long userId) {

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        //根据用户id查询订单信息
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Order> orders = orderMapper.selectList(queryWrapper);

        // 反转订单lists
        Collections.reverse(orders);

        //遍历检查订单支付情况
        for (Order order : orders) {

            //查询当前未支付的订单中，是否有订单发生状态变更
            if (order.getStatus() == 0) {

                //查询订单信息
                String res = payUtil.getPayInfo(order);

                //res为空字符串表示请求出错
                if (res.length() != 0) {

                    //如果检查到该订单已支付
                    if(res.equals("TRADE_SUCCESS")) {
                        //更新订单状态,将订单设为已支付
                        queryWrapper.eq("id",order.getId());
                        order.setStatus(1);
                        orderMapper.update(order,queryWrapper);
                    }

                    //如果检测到订单已过期关闭
                    if(res.equals("TRADE_CLOSED") || res.equals("TRADE_FINISHED")) {
                        //更新订单状态，将订单设为已关闭
                        queryWrapper.eq("id",order.getId());
                        order.setStatus(2);
                        orderMapper.update(order,queryWrapper);
                    }

                    //如果查询不到订单
                    if(res.equals("40004")){
                        //更新订单状态，将订单设为未支付
                        queryWrapper.eq("id",order.getId());
                        order.setStatus(0);
                        orderMapper.update(order,queryWrapper);
                    }
                }
            }
            //去除不必要信息
            order.setPage(null);
        }

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(orders);
        return resultUtil;
    }
}
